<?php
namespace app\teacher\controller;

use app\common\model\TeacherBase;
use app\teacher\model\TeacherManager;

class Login extends TeacherBase
{
    const MISS_NAME = "请输入姓名";
    const MISS_NUMBER = "请输入学号";
    const NON_EXIST = "用户不存在";

    const MISS_TOKEN = "请输入token";

    private $teacherManager;
    public function __construct()
    {
        $_SERVER["HTTP_X_TOKEN"] = "none";
        parent::__construct();
        $this->teacherManager = new TeacherManager();
    }

    /**
     *
     * @api {post} /teacher/login 教师账号登录
     * @apiDescription 教师账号登录
     * @apiGroup teacher
     * @apiParam {string} username 用户名
     * @apiParam {string} password 密码
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "username": 用户名，
     *       "password": 密码
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg token令牌，之后的接口在http请求中在header里加上HTTP-X-TOKEN=>TOKEN.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "token"
     *     }
     *
     */
    public function index(){
        $username = $_POST["username"];
        $password = $_POST["password"];

        if(!isset($username)){
            echoJson(0, "用户名为空");
        }else if(!isset($password)){
            echoJson(0, "密码为空");
        }

        $result = $this->teacherManager->checkLogin($username, $password);
        if($result){
            echoJson(1, $this->jwt->teacher_encode($username,$result["permission"]));
        }else{
            echoJson(0, self::NON_EXIST);
        }
    }

    /**
     *
     * @api {get} /teacher/login/valid_token 验证token有效性
     * @apiDescription 验证token有效性
     * @apiGroup teacher
     * @apiParam {string} token token
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "token": token，
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 验证token有效性,返回token中信息
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "token中信息"
     *     }
     *
     */
    public function valid_token(){
        $token = $_GET["token"];

        if(!isset($token)){
            echoJson(0, self::MISS_TOKEN);
        }

        echoJson(1,$this->jwt->decode($token));
    }
}